# backend/utils/cache.py
import redis
from backend.core.config import settings
import logging

logger = logging.getLogger(__name__)

try:
    # 创建Redis连接参数 - 只在有密码时添加密码
    redis_kwargs = {
        'host': settings.REDIS_HOST,
        'port': settings.REDIS_PORT,
        'db': settings.REDIS_DB,
        'decode_responses': True,
        'socket_connect_timeout': 5,
        'socket_timeout': 5
    }

    # 只有在有密码且不为空字符串时才添加密码
    if settings.REDIS_PASSWORD and settings.REDIS_PASSWORD.strip():
        redis_kwargs['password'] = settings.REDIS_PASSWORD
        logger.info("使用密码连接Redis")
    else:
        logger.info("无密码连接Redis")

    # 创建Redis客户端
    redis_client = redis.Redis(**redis_kwargs)

    # 测试连接
    redis_client.ping()
    logger.info("✅ Redis连接成功")

except Exception as e:
    logger.error(f"❌ Redis连接失败: {e}")
    redis_client = None


# 其余函数保持不变...
def set_captcha(token: str, correct_offset: int, expire_minutes: int = 5):
    if not redis_client:
        raise Exception("Redis未连接")
    key = f"captcha:{token}"
    expire_time = expire_minutes * 60
    redis_client.setex(key, expire_time, str(correct_offset))


def get_captcha(token: str) -> int:
    if not redis_client:
        return None
    key = f"captcha:{token}"
    value = redis_client.get(key)
    return int(value) if value else None


def delete_captcha(token: str):
    if not redis_client:
        return
    redis_client.delete(f"captcha:{token}")


def increment_attempt(token: str) -> int:
    if not redis_client:
        return 0
    key = f"captcha:attempt:{token}"
    count = redis_client.incr(key)
    if count == 1:
        redis_client.expire(key, 300)
    return count